<template>
  <div>
    <table class="table table-bordered">
      <thead>
        <tr>
          <th>
            <input type="checkbox" v-model="flag" @change="changeAll" />全选/反选
          </th>
          <th>商品名称</th>
          <th>商品图片</th>
          <th>商品单价</th>
          <th>商品数量</th>
          <th>商品价格</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item,index) in cartList" :key="index">
          <td>
            <input type="checkbox" v-model="item.status" @change="changeOne" />
          </td>
          <td>{{item.name}}</td>
          <td>
            <img :src="item.img" alt />
          </td>
          <td>{{item.pricr}}</td>
          <td>{{item.num}}</td>
          <td>{{(item.num * item.price).toFixed(2)}}</td>
          <td>
            <button type="button" class="btn btn-danger" @click="del(index)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
    <p>金额：￥{{js.money}}---------数量：{{js.number}}</p>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";
export default {
  name: "MyappIndex",

  data() {
    return {
      flag: false,
    };
  },
  computed: {
    ...mapGetters(["cartList"]),
    js() {
      let sum = this.cartList.reduce(
        (prev, item, index) => {
        //   console.log(123);
          if (item.status) {
            prev.money += parseFloat(item.price) * parseInt(item.num);
            prev.number += parseInt(item.num);
          }
          return prev;
        },
        { money: 0, number: 0 }
      );
      return sum;
    },
  },
  mounted() {},

  methods: {
      ...mapMutations(['del']),
    changeOne() {
      this.flag = this.cartList.every((item) => item.status);
      this.$store.dispatch("addCart", this.cartList);
    },
    changeAll(val){
        if(this.flag == true){
            this.cartList.filter(item=>item.status +=val)
        }else{
            this.cartList.forEach(item => {
                item.status=false
            })
        }
    }
  },
};
</script>

<style lang="scss" scoped>
img {
  width: 100px;
}
</style>